from django.shortcuts import render
from django.views import View
from apps.verifications.libs.captcha.captcha import captcha
from django_redis import get_redis_connection
import json, random
from django import http
from apps.verifications.libs.yuntongxun.ccp_sms import CCP


# Create your views here.
class SmsCodeView(View):
    def post(self, request):
        redis_conn = get_redis_connection('verify_code')
        json_dict = json.loads(request.body.decode())
        mobile = json_dict.get('mobile')
        id = json_dict.get('id')
        text = json_dict.get('text')
        image_code_server = redis_conn.get('img_%s' % id)
        redis_conn.delete('img_%s' % id)
        if not all([mobile, id, text]):
            return http.JsonResponse({'errno': '4103', 'errmsg': '缺少必传参数'})
        if not image_code_server:
            return http.JsonResponse({'errno': 4002, 'errmsg': '图形验证码失效'})
        image_code_server = image_code_server.decode()

        if image_code_server.lower() != text.lower():
            return http.JsonResponse({'code': 4103, 'errmsg': '图形验证码有误'})
        sms_code = '%06d' % random.randint(0, 999999)
        print(sms_code)
        CCP().send_template_sms(mobile, [sms_code, 5], 1)
        pl = redis_conn.pipeline()
        pl.setex('sms_%s' % mobile, 300, sms_code)
        pl.setex('send_flag_%s' % mobile, 60, 1)
        pl.execute()
        return http.JsonResponse({"errno": "0", "errmsg": "发送成功"})


class ImageCodeView(View):
    def get(self, request):
        uuid = request.GET.get('cur')
        pre = request.GET.get('pre')
        if not uuid:
            return http.JsonResponse({'errno': '4103', 'errmsg': '缺少必传参数'})
        text, image = captcha.generate_captcha()
        redis_conn = get_redis_connection('verify_code')
        redis_conn.setex('img_%s' % uuid, 300, text)
        return http.HttpResponse(image, content_type='image/jpg')
